<script setup>
  import {reactive, ref} from "vue";
  import adminApi from "@/api/adminApi.js";
  import {ElMessage, ElMessageBox} from "element-plus";
  import {Delete, Edit, Iphone} from "@element-plus/icons-vue";
  import router from "@/router/index.js";
  let admins = ref([])
  let pageInfo = reactive({
    page:1,
    limit:10,
    total:0,
    name:'',
    phone:''
  })
    /*显示管理员列表*/
  showAdmins()
  function showAdmins(){
    adminApi.getAdmin(pageInfo).then(response=>{
      admins.value=response.data.list
      pageInfo.total=response.data.total
    })
  }
  /*修改Size*/
  function handleSizeChange(val){
    pageInfo.limit=val
    showAdmins()
  }
  /*修改当前页*/
  function handleCurrentChange(val){
    pageInfo.page = val
    showAdmins()
  }
  /*搜索*/
  function onSearch(){
    adminApi.getAdmin(pageInfo).then(response=>{
      admins.value=response.data.list
      pageInfo.total=response.data.total
    })
  }
  /*显示弹窗*/
  let addVisible = ref(false)
  function showAdd(){
    addVisible.value=true
  }
  /*添加管理员*/
  let addAdmin = reactive({
    name:'',
    password:'',
    phone:''
  })
  function handleAdd(){
    if (!checkPhone(addAdmin.phone)) return
    if (!checkPassword()) return
    if (!checkPassword2()) return
    adminApi.addAdmin(addAdmin).then(response=>{
      if (response.code===200){
        ElMessage({
          message: '添加成功',
          type: 'success',
        })
        addAdmin.name=''
        addAdmin.password=''
        addAdmin.phone=''
        cPassword.value=''
        addVisible.value=false
        location.reload()
      }else {
        ElMessage.error('添加失败')
      }
    })
  }
  /*检查用户名是否存在*/
  function checkPhone(phone){
    const regex = /^1[3-9]\d{9}$/;
    if (!regex.test(phone)) {
      ElMessage.error('请输入有效的手机号')
      addAdmin.phone=''
      return false;
    }
    if (phone !== ''){
      adminApi.checkPhone(phone)
          .then(response=>{
            if (response.code===402){
              ElMessage.error(response.msg)
              addAdmin.phone=''
            }
          })
    }else {
      ElMessage.error('手机号不能为空')
      return false
    }
    return true
  }
  /*校验密码*/
  function checkPassword(){
    console.log(addAdmin.password)
    if (addAdmin.password===null || addAdmin.password===''){
      ElMessage.error('密码不能为空')
      return false
    }
    return true
  }
  /*检查两次密码是否相等*/
  const cPassword = ref('')
  function checkPassword2(){
    if (cPassword.value===null || cPassword.value===''){
        ElMessage.error('确认密码不能为空')
      return false
    }
    if (cPassword.value!==addAdmin.password){
      ElMessage.error('两次密码不一致')
      return false
    }
    return true
  }
  /*显示编辑*/
  const editVisible = ref(false)
  let editAdmin = reactive({})
  function showEdit(row){
    editVisible.value =true
    editAdmin=row
    editAdmin.password=''
  }
  /*修改管理员信息*/
  function handleEdit(){
    const regex = /^1[3-9]\d{9}$/;
    if (!regex.test(editAdmin.phone)) {
      ElMessage.error('请输入有效的手机号')
      editAdmin.phone=''
      return false;
    }
    if (editAdmin.name===null||editAdmin.name===''){
      ElMessage.error('名称不能为空')
      return
    }
    if (editAdmin.phone===null||editAdmin.phone===''){
      ElMessage.error('手机号不能为空')
      return
    }
    adminApi.modifyAdmin(editAdmin)
        .then(response=>{
          if (response.code===200){
            ElMessage({
              message:'修改成功',
              type:'success'
            })
            editVisible.value = false
            location.reload()
          }else{
            ElMessage.error(response.msg)
          }
        })
        .catch(e=>{
          ElMessage.error('请求异常')
        })
  }
  /*取消修改*/
  function cancel(){
    editVisible.value = false
    location.reload()
  }
  /*删除管理员*/
  function del(admin){
    ElMessageBox.confirm(
        '确定要删除吗？',
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
    )
        .then(() => {
          adminApi.deleteAdmin(admin.id)
              .then(response=>{
                if (response.code===200) {
                  ElMessage.success('删除成功')
                }else{
                  ElMessage.error('删除失败')
                }
                showAdmins()
              }).catch(()=>{
            ElMessage.error('请求异常')
          })
        })
        .catch(() => {
          ElMessage({
            type: 'info',
            message: '取消删除',
          })
        })
  }
  //获取登录用户
  getLoginAdmin();
  let loginAdmin = reactive({})
  function getLoginAdmin(){
    adminApi.getLoginAdmin().then(result=>{
      if (result.code === 200) {
        loginAdmin.name = result.data.name;
        //router.push('/charts')
      } else {
        router.push('/login')
      }
    });
  }
</script>

<template>
      <!-- 根据姓名和手机号搜索 -->
      <div class="flex gap-4 mb-4">
        &nbsp;&nbsp;
        <span>手机号</span>
        <el-input
            v-model="pageInfo.phone"
            style="width: 240px"
            placeholder="请输入手机号"
            :suffix-icon="Iphone"
        />
        &nbsp;&nbsp;
        <span>姓名</span>
        <el-input
            v-model="pageInfo.name"
            style="width: 240px"
            placeholder="请输入姓名"
        />
        &nbsp;&nbsp;
        <el-button type="primary" @click="onSearch"><el-icon><Search /></el-icon></el-button>
        &nbsp;&nbsp;&nbsp;&nbsp;
        <!-- 添加教练按钮 -->
        <el-button type="success" @click="showAdd" v-if="loginAdmin.name==='管理员'">创建管理员</el-button>
      </div>
        <!--管理员列表-->
      <div>
      <el-table
          :data="admins"
          row-key="id"
          style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="180" />
        <el-table-column prop="phone" label="手机号" width="180" />
        <el-table-column prop="name" label="姓名" />
        <el-table-column label="操作" v-if="loginAdmin.name==='管理员'">
          <template #default="scope">
            <el-button size="small" type="success"
                       @click="showEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger"
                       @click="del(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      </div>
    <!--  分页    -->
  <div class="demo-pagination-block">
    <el-pagination
        v-model:current-page="pageInfo.page"
        v-model:page-size="pageInfo.limit"
        :page-sizes="[5, 10, 15, 20]"
        :size='"default"'
        :background="background"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageInfo.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </div>
    <!-- 添加的弹窗 -->
    <el-dialog v-model="addVisible" title="创建新管理员" width="500">
        <el-form :model="addAdmin">
            <el-form-item label="电话" :label-width="70">
                <el-input v-model="addAdmin.phone" autocomplete="off" @blur="checkPhone(addAdmin.phone)"/>
            </el-form-item>
            <el-form-item label="密码" :label-width="70">
                <el-input v-model="addAdmin.password" autocomplete="off" show-password @blur="checkPassword"/>
            </el-form-item>
            <el-form-item label="确认密码" :label-width="70">
                <el-input v-model="cPassword" autocomplete="off" show-password @blur="checkPassword2" />
            </el-form-item>
            <el-form-item label="姓名" :label-width="70">
                <el-input v-model="addAdmin.name" autocomplete="off" />
            </el-form-item>
                <el-input v-model="addAdmin.id" hidden="hidden" />
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="addVisible = false">取消</el-button>
                <el-button type="primary" @click="handleAdd">
                    创建
                </el-button>
            </div>
        </template>
    </el-dialog>

    <!-- 编辑的弹窗 -->
    <el-dialog v-model="editVisible" title="编辑管理员" width="500">
        <el-form :model="editAdmin">
            <el-form-item label="电话" :label-width="60">
                <el-input v-model="editAdmin.phone" autocomplete="off" />
            </el-form-item>
            <el-form-item label="密码" :label-width="60">
              <el-col :span="22">
                <el-input v-model="editAdmin.password" autocomplete="off" show-password/>
              </el-col>
            </el-form-item>
            <el-form-item label="姓名" :label-width="60">
                <el-input v-model="editAdmin.name" autocomplete="off" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="cancel">取消</el-button>
                <el-button type="primary" @click="handleEdit">
                    编辑
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<style scoped>
  div{
    margin: 10px 6px;
  }
</style>